package com.skyvin.nreceipts.receipts.controller;

import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.skyvin.nreceipts.common.controller.BaseController;
import com.skyvin.nreceipts.common.document.ReceiptUpload;
import com.skyvin.nreceipts.common.value.JQGridResponse;
import com.skyvin.nreceipts.common.value.MessageValue;
import com.skyvin.nreceipts.receipts.mongorepository.ReceiptUploadRepository;
import com.skyvin.nreceipts.receipts.service.ReceiptService;
import com.skyvin.nreceipts.receipts.service.ReceiptUploadService;

@Controller
@RequestMapping("recUpload")
public class ReceiptUploadController extends BaseController {

	private static Logger logger = Logger.getLogger(ReceiptUploadController.class);
	
	@Autowired 
	ReceiptService receiptsService;
	
	@Autowired 
	ReceiptUploadService receiptUploadService;
	
	@Autowired
	MongoTemplate mongoTemplate; 
	
	@Autowired
	ReceiptUploadRepository receiptUploadRepository;
	
	@RequestMapping(value = "/loadReceiptImage", method = RequestMethod.GET)
	public String loadReceiptImage(@RequestParam(value="id") String id, @RequestParam(value="text") String imageURL, Model model) {
		model.addAttribute("imageURL", imageURL);
		return "receipts/receiptimage";
	}
	
	@RequestMapping(value="/viewUploadedReceipts", method=RequestMethod.GET)
	@ResponseBody
	public JQGridResponse viewUploadedReceipts(@RequestParam("_search") Boolean search,
    		@RequestParam(value="filters", required=false) String filters,
    		@RequestParam(value="page", required=false) Integer page,
    		@RequestParam(value="rows", required=false) Integer rows,
    		@RequestParam(value="sidx", required=false) String sidx,
    		@RequestParam(value="sord", required=false) String sord) {
		
		List<ReceiptUpload> receiptUploadList = null;
		//Page<ReceiptUpload> receiptUploadPageList = null;
		
		JQGridResponse jqGridResponse = new JQGridResponse();
		Pageable pageRequest = new PageRequest(page-1, rows);
		long count = 0;
		int countOfReceiptUploadListReturned = 0;
		
		//receiptUploadPageList = receiptUploadRepository.findAll(pageRequest);
		Query query = new Query();
		query.addCriteria(Criteria.where("userPID").is(getCurrentUserPID()));
		query.skip((page-1) * rows);
		query.limit(rows);
		
		Query countQuery = new Query();
		countQuery.addCriteria(Criteria.where("userPID").is(getCurrentUserPID()));
		
		receiptUploadList = mongoTemplate.find(query, ReceiptUpload.class, receiptUploadService.getMyCollection(ReceiptUpload.class));
		if(receiptUploadList!= null) {
			countOfReceiptUploadListReturned = receiptUploadList.size();
		}
		count = mongoTemplate.count(new Query(), receiptUploadService.getMyCollection(ReceiptUpload.class));
		logger.info("Count : " + count);
		logger.info("Records retrieved : " + countOfReceiptUploadListReturned);
		//receiptUploadList = receiptUploadPageList.getContent();
		//receiptUploadDTOList = ReceiptUploadMapper.map(receiptUploadPageList);
		
		jqGridResponse.setPage(1);
		
		if(receiptUploadList!= null) {
			
			jqGridResponse.setRecords(countOfReceiptUploadListReturned);
			jqGridResponse.setTotal((int) count);
			jqGridResponse.setPage(page);
		}
		jqGridResponse.setRows(receiptUploadList);
		return jqGridResponse;
	}

	@RequestMapping(value = "/uploadReceiptImage", method = RequestMethod.POST)
	public @ResponseBody MessageValue handleFormUpload(
			@RequestParam("receiptImage") MultipartFile file) throws IOException {
		MessageValue message = new MessageValue();

			if (!file.isEmpty()) {
				// Creating receipt upload document. 
				ReceiptUpload receiptUpload = new ReceiptUpload();
				receiptUpload.setUserPID(getCurrentUserPID());
				receiptUpload.setReceiptFile((CommonsMultipartFile) file);
				
				receiptUploadService.uploadFileandSaveReceipt(receiptUpload);

				message.setMessage("File is uploaded...");
				message.setDetailedMessage("http://farm4.staticflickr.com/3510/3208351775_e06db18ee4.jpg");

			} else {
				message.setMessage("File is empty.. Could not upload");
			}
		return message;
	}
	
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public @ResponseBody MessageValue deleteReceiptUpload(@RequestParam("oper") String oper, @RequestParam("id") String receiptUploadPID) {
		MessageValue message = new MessageValue();
		receiptUploadService.deleteReceiptUpload(receiptUploadPID);
		
		message.setMessage("Receipt image deleted");
		return message;
	}
	
	@RequestMapping(value = "/getReceiptUpload/{receiptUploadId}", method = RequestMethod.GET)
	public @ResponseBody ReceiptUpload getReceiptUpload(@PathVariable(value = "receiptUploadId") String receiptUploadId) {
		ReceiptUpload receiptUpload = null;
		
		receiptUpload = receiptUploadService.getMyReceiptUpload(receiptUploadId);
		return receiptUpload;
	}
}
